import 'package:cms/components/single_items.dart';
import 'package:cms/views/list_views/state/single_list/list_cubit.dart';
import 'package:cms/views/list_views/state/single_list/list_state.dart';
import 'package:cms/models/single.dart';
import 'package:common/export/tools.dart';
import 'package:flutter/material.dart';
import 'package:common/export/bloc.dart';
import 'package:components/pull_down_refresh/main.dart';

class LaraPressSingleListView extends StatelessWidget {
  final int categoryId;
  final bool isCustomScrollView;
  final String searchKeyword;
  final bool showCategory;

  const LaraPressSingleListView({
    super.key,
    this.categoryId = 0,
    this.isCustomScrollView = true,
    this.searchKeyword = '',
    this.showCategory = true,
  });
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) =>
          ListCubit(categoryId: categoryId, searchKeyword: searchKeyword),
      child: Builder(builder: (context) => _buildPage(context)),
    );
  }

  Widget _buildView(BuildContext context, ListState state) {
    final cubit = BlocProvider.of<ListCubit>(context);
    if (isCustomScrollView) {
      return LaraPressPullRefresh(
        controller: state.refreshController,
        onRefresh: () => cubit.getList(isRefresh: true),
        builder: (context, physics) {
          return CustomScrollView(
            physics: state.isLoading
                ? const NeverScrollableScrollPhysics()
                : physics,
            slivers: [_buildListView(context, state)],
          );
        },
      );
    }
    return _buildListView(context, state);
  }

  Widget _buildListView(BuildContext context, ListState state) {
    return SliverList.separated(
      separatorBuilder: (context, index) {
        return SizedBox(height: .5.h);
      },
      itemCount: state.isLoading ? 6 : state.list.length,
      itemBuilder: (context, index) {
        return LaraPressRowImgSingleItem(
          single: state.isLoading ? SingleModel() : state.list[index],
          isLoading: state.isLoading,
          showCategory: showCategory,
          onTap: () {
            context.pushNamed(
              'cms-detail',
              pathParameters: {'id': state.list[index].id.toString()},
            );
          },
        );
      },
    );
  }

  Widget _buildPage(BuildContext context) {
    return BlocBuilder<ListCubit, ListState>(
      builder: (context, state) {
        return _buildView(context, state);
      },
    );
  }
}
